package cn.w.outdoor.lib.media;

import android.util.Log;

import java.util.concurrent.atomic.AtomicBoolean;

import cn.w.outdoor.lib.model.Trans_Package;
import cn.w.outdoor.lib.network.UDPTools;

public class H264VideoCollector {

    private final static String TAG = "VideoCollector";


    private final AtomicBoolean control = new AtomicBoolean(false);

    private H264VideoEncodeAndSendThread h264VideoEncoderThread = null;

    /**
     * 添加视频的原始数据内容
     */
    public void addOriginVideoData(byte[] data) {
        synchronized (control) {
            if (control.get()) {
                if (h264VideoEncoderThread != null) {
                    h264VideoEncoderThread.addOriginVideoData(data);
                }
            }
        }
    }

    private OnDataListener dataListener = null;

    public void startVideoEncoder(final String remoteIpAddr, final int remotePort) {
        startVideoEncoder(null, remoteIpAddr, remotePort);
    }

    public void startVideoEncoder(final OnDataListener dataListener, final String remoteIpAddr, final int remotePort) {
        synchronized (control) {
            if (!control.get()) {
                if (h264VideoEncoderThread == null) {
                    h264VideoEncoderThread = new H264VideoEncodeAndSendThread();
                    h264VideoEncoderThread.setDataListener(new OnDataListener() {
                        @Override
                        public void onData(Trans_Package trans_package) {
                            UDPTools.getInstance().sendMediaAsync(trans_package, remoteIpAddr, remotePort);
//                            Log.e(TAG, "onData: 发送数据内容到 " + remoteIpAddr + ":" + remotePort);
                            if (dataListener != null) {
//                                Log.e(TAG, "onData: 回调 dataListener ");
                                dataListener.onData(trans_package);
                            } else {
//                                Log.e(TAG, "onData: dataListener 为 NULL，不执行回调操作");
                            }
                        }
                    });
                    h264VideoEncoderThread.start();
                }
                control.set(true);
            } else {
                Log.e(TAG, "startVideoEncoder: ");
            }
        }
    }

    public void stopVideoEncoder() {
        synchronized (control) {
            if (control.get()) {
                if (h264VideoEncoderThread != null) {
                    h264VideoEncoderThread.stopEncoder();
                    try {
                        h264VideoEncoderThread.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    h264VideoEncoderThread = null;
                }
            }
        }
    }

}
